﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using AutonomicComputingLibrary.MAPE;

namespace AutonomicComputingLibrary.LogicalSensors
{
    public class CPUManagement //: AutonomicComputingLibrary.ICheckUp
    {


        //fields
        public int NumberOfProcessors { get; set; }

        public int UsagePercentage { get; set; }

        public int PercentageMin { get; set; }

        public int PercentageMax { get; set; }

        public int disable
        {
            get
                ; set
                    ; }

       public  CPUManagement(int MaxCPU = 99, int MinCPU = 0)
       {
           PercentageMin = MinCPU;
           PercentageMax = MaxCPU;

       }

        public string GetAlert()
        {
            throw new NotImplementedException();
        }

        public int pause
        {
            get
                ; set
                    ; }

        public event AlertHandler Alert;

         public void CheckUp()
        {


            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Check() == Health.Negative)
                {
                    ACLAlert aclal = new ACLAlert();
                    aclal.Alert = Health.Negative.ToString();
                    Alert(this, aclal);


                }
            }
        }

        public Health? Check()
        {
            try
            {
               ObjectQuery wmicpus = new WqlObjectQuery("SELECT * FROM Win32_Processor");
        ManagementObjectSearcher cpus = new ManagementObjectSearcher(wmicpus);
        
        
            int coreCount = 0;
            int totusage = 0;               
            foreach (ManagementObject cpu in cpus.Get())
            {
                
                totusage += Convert.ToInt32(cpu["LoadPercentage"]);
            }
           


                

                

                float mem = totusage;

                return mem > PercentageMax || mem < PercentageMin
                           ? Health.Negative
                           : Health.Positive;
            }
            catch (Exception)
            {
                    
                return Health.UnableToDetermine;
            }
        }

        public void GetHealthHistory()
        {
            throw new NotImplementedException();
        }
    }
}
